import NProgress from 'nprogress'
import 'nprogress/nprogress.css' // progress bar style
import router from '@/router'
import { getToken } from '@/utils/auth'
import { useUserStoreHook } from '@/stores/user'
import { usePermissionStoreHook } from '@/stores/permission'
const whiteList = ['/login'] // no redirect whitelist
NProgress.configure({ showSpinner: false })

router.beforeEach(async (to, from, next) => {
  const accessToken = getToken()
  const userStore = useUserStoreHook()
  const permissionStore = usePermissionStoreHook()
  NProgress.start() // 这个是上面的进度条
  document.title = to.meta.title ?? '请稍后...'
  if (accessToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasRoles = userStore.user.addon_roles && userStore.user.addon_roles.length > 0 && permissionStore.isLoading
      console.log('hasRoles', userStore.user)
      if (hasRoles) {
        if (to.matched.length === 0) {
          from.name ? next({ name: from.name }) : next('/404')
        } else {
          next()
        }
      } else {
        try {
          // eslint-disable-next-line camelcase
          const { addon_roles } = await userStore.getUserInfo()
          const accessRoutes: any = await permissionStore.generateRoutes(addon_roles)
          accessRoutes.forEach((route) => {
            router.addRoute(route)
          })
          next({ ...to, replace: true })
        } catch (error) {
          console.log('error', error)
          userStore.resetToken()
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
